package com.whq.thrift.api.web.admin.controller.bs;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.whq.common.StringUtil;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;

/**
 * memcache 测试工具
 * 
 * @author whq-mac
 * 
 */

@Controller
@Scope("prototype")
public class MemcacheTestController {
	private static final Logger LOGGER = LoggerFactory.getLogger(MemcacheTestController.class);

	@RequestMapping(value = "bs/memcachetest/index")
	public String index(@RequestParam(value = "ipAddress", required = false) String ipAddress, @RequestParam(value = "port", required = false) String port,
			@RequestParam(value = "key", required = false) String key, Model model, HttpServletRequest request) {
		model.addAttribute("ipAddress", ipAddress);
		model.addAttribute("port", port);
		model.addAttribute("key", key);

		String val = "";
		if (StringUtil.isBlank(ipAddress) || StringUtil.isBlank(port) || StringUtil.isBlank(key)) {
			model.addAttribute("val", val);
			return "bs/memcachetest/index";
		}

		MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(ipAddress + ":" + port));

		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = builder.build();
		} catch (IOException e1) {
			val = e1.getMessage();
		}

		if (memcachedClient != null) {
			try {
				val = memcachedClient.get(key);
			} catch (MemcachedException e) {
				val = e.getMessage();
			} catch (TimeoutException e) {
				val = e.getMessage();
			} catch (InterruptedException e) {
				val = e.getMessage();
			}

			try {
				memcachedClient.shutdown();
			} catch (IOException e) {
				LOGGER.error("Shutdown MemcachedClient fail, exception: ", e);
			}
		}
		model.addAttribute("val", val);

		return "bs/memcachetest/index";
	}
}